package com.zxlfysj.search;


/**
 * 插值查找
 *
 * @author yangshujing
 * @create 2020-08-19 10:46
 */
public class InsertValueSearch {
    public static void main(String[] args) {
        int[] arr = {1, 3, 4, 6, 9, 11, 13,203, 303, 403};
        //测试
        int res = insertValueSearch(arr, 0, arr.length - 1, 403);
        System.out.println(res);
    }

    /**
     * @param arr     数组
     * @param left    左边索引
     * @param right   右边索引
     * @param findVal 查找值
     * @return  返回查找值的下标，没找到返回-1
     */
    public static int insertValueSearch(int[] arr, int left, int right, int findVal) {
        if (left > right || findVal < arr[0] || findVal > arr[arr.length - 1]) {
            return -1;
        }
        int mid = left + (right - left) * (findVal - arr[left]) / (arr[right] - arr[left]);
        int midVal = arr[mid];
        if (findVal > midVal) {
            return insertValueSearch(arr, mid + 1, right, findVal);
        } else if(findVal < midVal) {
            return insertValueSearch(arr, left, mid - 1, findVal);
        } else {
            return mid;
        }
    }
}
